<!--
 * @Descripttion: 
 * @version: 
 * @Author: Peanut
 * @Date: 2024-04-20 11:30:02
 * @LastEditors: Peanut
 * @LastEditTime: 2024-04-25 11:28:16
-->
<template>
  <div class="upload">
    <el-upload
      class="upload_demo"
      :action="action"
      :accept="accept"
      :before-upload="handleBeforeUpload"
      :on-change="handleChange"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
      :limit="limit"
      :file-list="files"
      :list-type="listType"
    >
      <el-button size="small" type="primary">{{ uploadText }}</el-button>
      <div
        slot="tip"
        class="el-upload__tip"
        style="color: #f04525"
        v-if="files.length == 0"
      >
        {{ uploadTip }}
      </div>
    </el-upload>
  </div>
</template>

<script>
export default {
  name: "upload",
  props: {
    action: {
      type: String,
      default: "",
    },
    uploadText: {
      type: String,
      default: "上传图片",
    },
    uploadTip: {
      type: String,
      default: "请上传图片，支持jpg/png等图片格式，最多上传1张",
    },
    limit: {
      type: Number,
      default: 1,
    },
    accept: {
      type: String,
      default: "*",
    },
    listType: {
      type: String,
      default: "picture",
    },
    //数据回显
    fileList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      //   action: "https://jsonplaceholder.typicode.com/posts/",
      // action: "",

      files: [
        // {
        //   name: "food.jpeg",
        //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
        // },
      ],
    };
  },
  methods: {
    handleBeforeUpload(file) {
      // if (file.size > 1048576 * 10) {
      //   this.$message.warning("请上传小于10MB的图片");
      //   return false;
      // }
      // const suffix = file.name?.slice(file.name?.lastIndexOf(".") + 1);
      // const reg = /jpg|png/i;
      // if (!reg.test(suffix)) {
      //   this.$message.warning("仅支持jpg、png等图片格式的图片！");
      //   return false;
      // }
    },
    handlePreview(file) {
      console.log(file, ">>>>>>");
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.$emit("onRemove");
    },
    handleExceed() {
      this.$emit("onExceed");
      // this.$message.warning(`最多上传${this.limit}张`);
    },
    handleChange(file) {
      console.log("ChangeFile>>>>", file);
      this.$emit("onChange", file);
    },
    handleSuccess(res, file, fileList) {
      console.log(res, ">>>>>>res===");
      this.files.push({
        name: file.name,
        url: file.url,
      });
      this.$emit("onSuccess", this.files);

      //   this.files.push();
    },
  },
  watch: {
    fileList: {
      handler(newVal) {
        this.files = [...newVal];
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>

<style scoped></style>
